package com.zygame.sdk.view.floatbutton;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.zygame.sdk.ConstantValue;
import com.zygame.sdk.bean.ConfigMessage;
import com.zygame.sdk.bean.ZY_Toolbar;
import com.zygame.sdk.utils.SharedPreferencesHelper;
import com.zygame.sdk.utils.log.LogHelper;
import com.zygame.sdk.utils.phone.Phoneuitl;
import com.zygame.sdk.utils.res.FYResource;
import com.zygame.sdk.utils.res.ResourceUtil;
import com.zygame.sdk.view.floatbutton.FloatToolBar.FloatToolBarAlign;
import com.zygame.sdk.view.web.ZY_Act_WebView;

import java.util.ArrayList;

/**
 * @ClassName:FloatWindow
 * @author
 */

public class FloatWindow extends ImageView {

	public static FloatWindow floatWindow;

	private static final String TAG = "FloatWindow";

	private static final String PREFS_FILE = "FloatWindow";

	private static final int UPDATEVIEW_TYPE_BUTTON = 0;

	private static final int UPDATEVIEW_TYPE_MENU = 1;
	// private static final int SIDEFLOATWINDOW = 2;

	/**
	 * 左边为true，右边为false
	 */
	private static final String ALIGN = "align";

	private static final String POSITION = "position";

	private Activity mActivity;

	private FloatToolBarAlign mFloatToolBarAlign;

	private float mPosition;

	private boolean isMenuShow = false;

	private boolean ifSide = false; // 按钮是否隐藏到边边

	/**
	 * 按钮
	 */
	public WindowManager.LayoutParams mButtonWmParams;

	private WindowManager.LayoutParams mMenuWmParams;

	// 创建浮动窗口设置布局参数的对象
	private WindowManager mWindowManager;

	/**
	 * 最小移动距离
	 */
	private final static double DISTANCE = 9;

	/**
	 * 按下时的坐标偏移
	 */
	private double mStartX, mStartY;

	/**
	 * 触摸点坐标
	 */
	private double mTouchX, mTouchY;

	/**
	 * 屏幕高宽
	 */
	private int mScreenHeight, mScreenWidth;

	private float mDensity;

	/**
	 * 按钮背景
	 */
	// private Drawable mIconNormal;
	private Drawable mIconActive, mIconExpanded;

	private Drawable mIconSideLeft, mIconSideRight;

	// private Drawable mBitmapRightDrawable, mBitmapLiftDrawable;

	private FloatMenu mFloatMenu;

	/**
	 * 是否移动中
	 */
	private boolean mMoving = false;

	/**
	 * 速度
	 */
	private final static int SPEED = 20;

	private int mSpeed;

	private final static int TIME = 10;

	CountDownTimer countDownTimer;

	/**
	 * 配置文件
	 */
	private SharedPreferences mSharedPreferences;

	/**
	 * 创建一个新的实例 FloatWindow.
	 * 
	 * @param context
	 * @param attrs
	 * @param defStyle
	 */

	private FloatWindow(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	/**
	 * 创建一个新的实例 FloatWindow.
	 * 
	 * @param context
	 * @param attrs
	 */

	private FloatWindow(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	/**
	 * 创建一个新的实例 FloatWindow.
	 * 
	 * @param context
	 */

	private FloatWindow(Context context) {
		super(context);
	}

	/**
	 * @param activity
	 * @param showlasttime
	 *            是否显示上次位置
	 * @param align
	 *            对齐方式
	 * @param position
	 *            位置，相对于屏幕高百分比
	 */
	FloatWindow(Activity activity, boolean showlasttime, FloatToolBarAlign align, float position) {
		super(activity);
		this.mActivity = activity;
		this.mFloatToolBarAlign = align;
		this.mPosition = position;

		mSharedPreferences = activity.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);

		if (showlasttime) {
			boolean sides = mSharedPreferences.getBoolean(ALIGN, true);
			if (sides) {
				this.mFloatToolBarAlign = FloatToolBarAlign.Left;
			} else {
				this.mFloatToolBarAlign = FloatToolBarAlign.Right;
			}
			this.mPosition = mSharedPreferences.getFloat(POSITION, 0.1f);
		} else {
			Editor sharedPreferencesEdit = activity.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE).edit();
			position = 0.1f;
			sharedPreferencesEdit.putFloat(POSITION, position);
			if (align == FloatToolBarAlign.Right) {
				sharedPreferencesEdit.putBoolean(ALIGN, false);
			} else {
				sharedPreferencesEdit.putBoolean(ALIGN, true);
			}
			sharedPreferencesEdit.commit();
		}
		countDownTimer = new CountDownTimer(3000, 3000) {

			@Override
			public void onTick(long millisUntilFinished) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
				if (mMoving == false && isMenuShow == false) {
					ifSide = true;
					hideMenu();
					if (mFloatToolBarAlign == FloatToolBarAlign.Left) { // 左边
						floatWindow.setImageDrawable(mIconSideLeft);
					} else {
						floatWindow.setImageDrawable(mIconSideRight);
					}
				}
			}
		};

		setSide();
		initVariables();
		initViews();
		initButtonWindow();
		initMenuWindow();
	}

	/**
	 * 
	 * @param activity
	 * @param showlasttime
	 * @param align
	 * @param position
	 * @return
	 */
	public static FloatWindow getInstance(Activity activity, boolean showlasttime, FloatToolBarAlign align, float position) {
		if (floatWindow == null) {
			// synchronized (ConfigMessage.class) {
			if (floatWindow == null) {
				floatWindow = new FloatWindow(activity, showlasttime, align, position);
				// }
			}
		}
		return floatWindow;
	}

	public static FloatWindow getInstance() {
		return floatWindow;
	}

	public void setParams(Activity activity, boolean showlasttime, FloatToolBarAlign align, float position) {
		mSharedPreferences = activity.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);

		if (showlasttime) {
			boolean sides = mSharedPreferences.getBoolean(ALIGN, true);
			if (sides) {
				this.mFloatToolBarAlign = FloatToolBarAlign.Left;
			} else {
				this.mFloatToolBarAlign = FloatToolBarAlign.Right;
			}
			this.mPosition = mSharedPreferences.getFloat(POSITION, 0);
		} else {
			Editor sharedPreferencesEdit = activity.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE).edit();
			sharedPreferencesEdit.putFloat(POSITION, position);
			if (align == FloatToolBarAlign.Right) {
				sharedPreferencesEdit.putBoolean(ALIGN, false);
			} else {
				sharedPreferencesEdit.putBoolean(ALIGN, true);
			}
			sharedPreferencesEdit.commit();
		}
	}

	/**
	 * 初始化变量
	 * 
	 * @author
	 */
	private void initVariables() {
		mScreenHeight = getResources().getDisplayMetrics().heightPixels;
		mScreenWidth = getResources().getDisplayMetrics().widthPixels;
		mDensity = getResources().getDisplayMetrics().density;
		// 获取的是WindowManagerImpl.CompatModeWrapper
		// 只是属于Activity的LocalWindowManager

		mWindowManager = (WindowManager) mActivity.getSystemService(Context.WINDOW_SERVICE);
		Bitmap mIconActiveBm = BitmapFactory.decodeResource(mActivity.getResources(), ResourceUtil.getDrawableId(mActivity, FYResource.drawable.fy_suspension_active_btn));
		mIconActive = new BitmapDrawable(Phoneuitl.bitmapAdaptive(mActivity, mIconActiveBm));

		Bitmap mIconExpandedBm = BitmapFactory.decodeResource(mActivity.getResources(), ResourceUtil.getDrawableId(mActivity, FYResource.drawable.fy_suspension_after_btn));
		mIconExpanded = new BitmapDrawable(Phoneuitl.bitmapAdaptive(mActivity, mIconExpandedBm));

		Bitmap sideLeftBm = BitmapFactory.decodeResource(mActivity.getResources(), ResourceUtil.getDrawableId(mActivity, FYResource.drawable.fy_suspension_side_left));
		mIconSideLeft = new BitmapDrawable(Phoneuitl.bitmapAdaptive(mActivity, sideLeftBm));

		Bitmap sideRightBm = BitmapFactory.decodeResource(mActivity.getResources(), ResourceUtil.getDrawableId(mActivity, FYResource.drawable.fy_suspension_side_right));
		mIconSideRight = new BitmapDrawable(Phoneuitl.bitmapAdaptive(mActivity, sideRightBm));
	}

	/**
	 * 初始化视图
	 * 
	 * @author
	 */
	private void initViews() {
		setImageDrawable(mIconActive);
		setClickable(true);
		setId(android.R.id.toggle);
		mFloatMenu = new FloatMenu(mActivity);
	}

	/**
	 * 初始化WindowManager
	 * 
	 * @author
	 */
	private void initButtonWindow() {
		mButtonWmParams = new WindowManager.LayoutParams();
		// 设置window type
		mButtonWmParams.type = WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
		// 设置图片格式，效果为背景透明
		mButtonWmParams.format = PixelFormat.RGBA_8888;
		// 设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
		mButtonWmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;

		// mButtonWmParams.gravity = Gravity.LEFT |Gravity.TOP;
		// mButtonWmParams.windowAnimations = android.R.style.Animation_Toast;
		// mButtonWmParams.windowAnimations =
		// ResourceUtil.getStyleId(getContext(),
		// "floatwindowAnimationSideRight");
		// mButtonWmParams.windowAnimations = floatWindowSideAnimation();

		// 调整悬浮窗显示的停靠位置为左侧置顶
		if (mFloatToolBarAlign == FloatToolBarAlign.Right) {
			mButtonWmParams.gravity = Gravity.RIGHT | Gravity.TOP;
		} else {
			mButtonWmParams.gravity = Gravity.LEFT | Gravity.TOP;
		}

		// 设置悬浮窗口长宽数据
		// mButtonWmParams.width = (int) dpTopx(40);
		// mButtonWmParams.height = (int) dpTopx(40);
		mButtonWmParams.width = LayoutParams.WRAP_CONTENT;
		mButtonWmParams.height = LayoutParams.WRAP_CONTENT;
		setVisibility(View.GONE);
		mWindowManager.addView(this, mButtonWmParams);

		// BadgeView badge = new BadgeView(mActivity, this);
		// badge.setBadgePosition(BadgeView.POSITION_TOP_LEFT);
		// badge.setBackgroundResource(R.drawable.fy_msg_prompt);
		// badge.show();
	}

	private void initMenuWindow() {
		mMenuWmParams = new WindowManager.LayoutParams();
		// 设置window type
		mMenuWmParams.type = WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
		// 设置图片格式，效果为背景透明
		mMenuWmParams.format = PixelFormat.RGBA_8888;
		// 设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
		mMenuWmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
		// 设置窗口展示动画
		// mMenuWmParams.windowAnimations = android.R.style.Animation_Toast;
		setFloatMenubackground(mFloatToolBarAlign);
		mFloatMenu.setVisibility(View.GONE);
		mWindowManager.addView(mFloatMenu, mMenuWmParams);
	}

	/**
	 * 设置位置
	 * 
	 * @author
	 * @param tempX
	 * @param tempY
	 */

	private void setPosition(double tempX, double tempY) {
		mButtonWmParams.x = (int) tempX;
		mButtonWmParams.y = (int) (tempY - getStatusBarHeight());

		LogHelper.d(TAG + "setPosition---mButtonWmParams.y", "" + mButtonWmParams.y);
		// 刷新
		handler.sendEmptyMessage(UPDATEVIEW_TYPE_BUTTON);
	}

	/**
	 * 两边靠
	 * 
	 * @author
	 * @param side
	 */
	private void alongSides(final FloatToolBarAlign side) {
		mMoving = true;
		mSpeed = (int) (SPEED * mDensity);
		new Thread() {
			public void run() {
				if (mFloatToolBarAlign == side) {
					while (mButtonWmParams.x > 0) {
						mButtonWmParams.x = mButtonWmParams.x - mSpeed;
						mButtonWmParams.x = mButtonWmParams.x <= 0 ? 0 : mButtonWmParams.x;
						try {
							sleep(TIME);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						handler.sendEmptyMessage(UPDATEVIEW_TYPE_BUTTON);
					}

				} else {
					while (mButtonWmParams.x < mScreenWidth) {
						mButtonWmParams.x = mButtonWmParams.x + mSpeed;
						mButtonWmParams.x = mButtonWmParams.x > mScreenWidth ? mScreenWidth : mButtonWmParams.x;
						try {
							sleep(TIME);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						handler.sendEmptyMessage(UPDATEVIEW_TYPE_BUTTON);
					}
				}
				mFloatToolBarAlign = side;
				if (mFloatToolBarAlign == FloatToolBarAlign.Left) {
					mButtonWmParams.gravity = Gravity.LEFT | Gravity.TOP;
				} else if (mFloatToolBarAlign == FloatToolBarAlign.Right) {
					mButtonWmParams.gravity = Gravity.RIGHT | Gravity.TOP;
				} else {
					mButtonWmParams.gravity = Gravity.LEFT | Gravity.TOP;
				}
				mButtonWmParams.x = 0;
				mMoving = false;
				handler.sendEmptyMessage(UPDATEVIEW_TYPE_BUTTON);
			};
		}.start();

	}

	// TODO
	private Handler handler = new Handler() {
		@SuppressLint("NewApi")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATEVIEW_TYPE_BUTTON:
				mWindowManager.updateViewLayout(floatWindow, mButtonWmParams);
				break;
			case UPDATEVIEW_TYPE_MENU:
				mWindowManager.updateViewLayout(mFloatMenu, mMenuWmParams);
				break;
			// case SIDEFLOATWINDOW:
			// // isMenuShow = true;
			// if (mMoving == false && isMenuShow == false) {
			// ifSide = true;
			// if (mFloatToolBarAlign == FloatToolBarAlign.Left) { // 左边
			// floatWindow.setImageDrawable(mIconSideLeft);
			// } else {
			// floatWindow.setImageDrawable(mIconSideRight);
			// }
			// }
			// break;
			default:
				break;
			}
		};
	};

	/**
	 * 保存位置
	 * 
	 * @author
	 * @param align
	 * @param position
	 */
	private void savePosition(boolean align, float position) {
		position = position / mScreenHeight * 1.0f;
		Editor sharedPreferencesEdit = mActivity.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE).edit();
		sharedPreferencesEdit.putBoolean(ALIGN, align);
		sharedPreferencesEdit.putFloat(POSITION, position);
		sharedPreferencesEdit.commit();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		double tempX, tempY, temp;
		if (mMoving) {
			return false;
		}
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			// setImageDrawable(mIconExpanded);
			int[] location = new int[2];
			getLocationOnScreen(location);
			double x = location[0];
			double y = location[1];
			mTouchX = event.getRawX();
			mTouchY = event.getRawY();
			mStartX = mTouchX - x;
			mStartY = mTouchY - y;
			break;
		case MotionEvent.ACTION_MOVE:
			tempX = event.getRawX();
			tempY = event.getRawY();
			temp = Math.pow(mTouchX - tempX, 2) + Math.pow(mTouchY - tempY, 2);
			if (Math.sqrt(temp) > DISTANCE) {
				hideMenu();
				mTouchX = tempX;
				mTouchY = tempY;
				if (mFloatToolBarAlign == FloatToolBarAlign.Left) {
					setPosition(tempX - mStartX, tempY - mStartY);
				} else {
					setPosition(mScreenWidth - (tempX + mStartX), tempY - mStartY);
				}
			}
			break;
		case MotionEvent.ACTION_UP:
			// setImageDrawable(mIconActive);
			if (!mMoving) {
				mMoving = false;
				int[] position = new int[2];
				getLocationOnScreen(position);
				if ((position[0] + getMeasuredWidth() / 2) <= mScreenWidth / 2) { // 判断浮动图标在屏幕左边
					alongSides(FloatToolBarAlign.Left);
					savePosition(true, position[1] + getMeasuredHeight() / 2.0f);
				} else {
					alongSides(FloatToolBarAlign.Right);
					savePosition(false, position[1] + getMeasuredHeight() / 2.0f);
				}
				setSide();
			}

			break;
		}
		return detector.onTouchEvent(event);
	}

	private void setSide() {
		if (countDownTimer != null) {
			countDownTimer.cancel();
			countDownTimer.start();
		}
	}

	private GestureDetector detector = new GestureDetector(mActivity, new SimpleOnGestureListener() {

		// 触发触摸事件
		public boolean onSingleTapConfirmed(MotionEvent e) {
//			if (TextUtils.isEmpty(UserModel.getInstance().getToken())) {
//				ToastUtil.showToast(mActivity, "请先登录...");
//				CmGameSDK.getInstance().login();
//				return false;
//			}
			int location[] = new int[2];
			getLocationOnScreen(location);
			int y = (int) (location[1] + getMeasuredHeight() / 2.0f - mFloatMenu.getMeasuredHeight() / 2);
			int x = getMeasuredWidth();
			if (ifSide) {
				ifSide = false;
				setImageDrawable(mIconActive);
				hideMenu();
				return false;
			} else {
				showMenu(x, y);
			}
			return false;
		};

		public void onLongPress(MotionEvent e) {
//			new HideFloatButtonDialog(mActivity).show();
//			new ZY_DialogTip(mActivity).show();

		};
	});

	/**
	 * 显示浮动条
	 * 
	 * @author
	 */
	private void showMenu(int x, int y) {
		isMenuShow = true;
		x = (int) (x - 8 * mDensity) + 5;
		setImageDrawable(mIconActive);
		if (mWindowManager == null || mMenuWmParams == null || mFloatMenu == null) {
			return;
		}
		if (mFloatMenu.getVisibility() == View.VISIBLE) {
			hideMenu();
			return;
		}
		mMenuWmParams.y = y - getStatusBarHeight();
		// mMenuWmParams.x = x;
		mMenuWmParams.x = x - 30;
		setFloatMenubackground(mFloatToolBarAlign);
		mMenuWmParams.gravity = mButtonWmParams.gravity;
		if (mFloatToolBarAlign == FloatToolBarAlign.Left) { // 设置浮动条显示动画
			mMenuWmParams.windowAnimations = ResourceUtil.getStyleId(getContext(), "actionSheetAnimationLeft");
		} else {
			mMenuWmParams.windowAnimations = ResourceUtil.getStyleId(getContext(), "actionSheetAnimationRight");
		}
		mFloatMenu.setVisibility(View.VISIBLE);
		handler.sendEmptyMessage(UPDATEVIEW_TYPE_MENU);
	}

	// public void popupWindwShowing() {
	// // 将selectPopupWindow作为parent的下拉框显示，并指定selectPopupWindow在Y方向上向上偏移3pix，
	// // 这是为了防止下拉框与文本框之间产生缝隙，影响界面美化
	// // （是否会产生缝隙，及产生缝隙的大小，可能会根据机型、Android系统版本不同而异吧，不太清楚）
	// selectPopupWindow.showAsDropDown(fy_login_ll_userNameRoot, 0, -3);
	// }

	private void setFloatMenubackground(FloatToolBarAlign align) {
		if (align == FloatToolBarAlign.Right) {
			Bitmap bitmap = BitmapFactory.decodeResource(mActivity.getResources(), ResourceUtil.getDrawableId(mActivity, FYResource.drawable.fy_menu_right_bg));
			mFloatMenu.setBackgroundDrawable(new BitmapDrawable(Phoneuitl.bitmapAdaptive(mActivity, bitmap, 2)));
		} else {
			Bitmap bitmap = BitmapFactory.decodeResource(mActivity.getResources(), ResourceUtil.getDrawableId(mActivity, FYResource.drawable.fy_menu_left_bg));
			mFloatMenu.setBackgroundDrawable(new BitmapDrawable(Phoneuitl.bitmapAdaptive(mActivity, bitmap, 2)));
		}
		// mFloatMenu.setPadding(mFloatMenu.getPaddingLeft(), 5,
		// mFloatMenu.getPaddingRight(), 5);
		// 设置悬浮窗口长宽数据
		mMenuWmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
		// mMenuWmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
		mMenuWmParams.height = (int) dpTopx(45);
	}

	/**
	 * 隐藏菜单
	 * 
	 * @author
	 */
	public void hideMenu() {
		isMenuShow = false;
		setImageDrawable(mIconActive);
		if (mWindowManager == null || mMenuWmParams == null || mFloatMenu == null) {
			return;
		}
		mFloatMenu.startAnimation(floatMenuOutScaleAnimation());
		mFloatMenu.setVisibility(View.GONE);
		// side();
	}

	/**
	 * 获取状态栏高度
	 * 
	 * @author
	 * @return
	 */
	private int getStatusBarHeight() {
		Rect frame = new Rect();
		mActivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
		return frame.top;
	}

	/**
	 * 隐藏
	 * 
	 * @author
	 */
	public void hide() {
		if (!isShowing()) {
			return;
		}
		hideMenu();
		floatWindow.setVisibility(GONE);
	}
	public void remove() {
//		if (mWindowManager != null) {
//			if(null !=mFloatMenu){
//				mWindowManager.removeViewImmediate(mFloatMenu);
//			}
//
//			mWindowManager.removeViewImmediate(this);
//		}

		if (mWindowManager != null) {
			mWindowManager.removeViewImmediate(this);
			mButtonWmParams = null;
			if (mFloatMenu != null) {
				mWindowManager.removeViewImmediate(mFloatMenu);
				mMenuWmParams = null;
			}
		}
	}

	public void clear() {
		floatWindow = null;
	}

	/**
	 * 显示
	 * 
	 * @author
	 */
	public void show() {
		if (mWindowManager == null || mButtonWmParams == null) {
			return;
		}
		mPosition = mSharedPreferences.getFloat(POSITION, 0.1f);

		// 以屏幕左上角为原点，设置x、y初始值，相对于gravity
		mButtonWmParams.x = 0;
		mPosition = mPosition < 0 ? 0 : mPosition;
		mPosition = mPosition > 1 ? 1 : mPosition;
		mButtonWmParams.y = (int) ((mScreenHeight - getStatusBarHeight()) * mPosition - mIconActive.getIntrinsicHeight() / 2);
		LogHelper.d(TAG + "mButtonWmParams.y", "" + mButtonWmParams.y);
		setVisibility(View.VISIBLE);
		handler.sendEmptyMessage(UPDATEVIEW_TYPE_BUTTON);
	}

	/**
	 * @author
	 */
	public void recycle() {
		try {
			if (mWindowManager != null) {
				mWindowManager.removeView(this);
				mButtonWmParams = null;
				if (mFloatMenu != null) {
					mWindowManager.removeView(mFloatMenu);
					mMenuWmParams = null;
				}
			}
		}catch (Exception e){

		}
		// 移除悬浮窗口

	}

	/**
	 * @return 是否显示
	 */
	public boolean isShowing() {
		if (mButtonWmParams == null) {
			return false;
		}
		if (getVisibility() == View.VISIBLE) {
			return true;
		} else {
			return false;
		}
	}

	private class FloatMenu extends LinearLayout {

		public FloatMenu(final Context context) {
			super(context);
			setGravity(Gravity.CENTER);
			setOrientation(LinearLayout.HORIZONTAL);
			ArrayList<ZY_Toolbar> mains = (ArrayList<ZY_Toolbar>) ConfigMessage.getInstance().getMainData();
			if (mains == null) {
				return;
			}

			setPadding((int) dpTopx(20), (int) dpTopx(0), (int) dpTopx(20), (int) dpTopx(0));

			for (ZY_Toolbar main : mains) {
				ImageView iv = new ImageView(context);

//				 if(main.id.equals("19")) continue; //隐藏 账户
				if(main.hide.equals("1")) continue;    // hide=0: 开启   hide=1: 关闭

//				iv.setPadding((int) dpTopx(2), (int) dpTopx(10), (int) dpTopx(2), 0);
//				ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(100, 100);
//				iv.setLayoutParams(layoutParams);
				// tv.setPadding((int) dpTopx(3), (int) dpTopx(11), (int)
				// dpTopx(3), 0);
				iv.setTag(main);
//				tv.setTextColor(Color.WHITE);
//				tv.setText("账号");
				iv.setOnClickListener(new FloatWindowClick());
				iv.setBackgroundResource(ResourceUtil.getDrawableId(context,"zy_select_user"));
//				tv.setCompoundDrawablesWithIntrinsicBounds(null,
//						ImageSelector.newSelector(context, Icons.getInstance().getIconsFromDrawable(context, "zy_d_new_more", 0), Icons.getInstance().getIconsFromDrawable(context, "zy_d_new_s_more", 1)), null, null);
				addView(iv);

				// if(main.id.equals("7")){
				// BadgeView badge = new BadgeView(context, tv);
				// badge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
				// Bitmap bitmap =
				// BitmapFactory.decodeResource(context.getResources(),
				// ResourceUtil.getDrawableId(context,
				// FYResource.drawable.fy_msg_prompt));
				// Bitmap b = Phoneuitl.bitmapAdaptive(context, bitmap, 2);
				// badge.setBackgroundDrawable(new BitmapDrawable(b));
				// badge.show();
				// }
			}
		}
	}

	class FloatWindowClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			ZY_Toolbar main = (ZY_Toolbar) v.getTag();
			SharedPreferencesHelper sp = SharedPreferencesHelper.getInstance();
			main.url = main.url+"?cid="+ConstantValue.ZY_CID+"&sid="+ConstantValue.ZY_SID+"&gid="+ConstantValue.ZY_GAMEID
					+"&language="+ConstantValue.ZY_LANGUAGE+"&token="+sp.getToken(mActivity)+"&login_token="+sp.getLogin_Token(mActivity);
			Intent intent = new Intent(getContext(), ZY_Act_WebView.class);
			intent.putExtra(ConstantValue.TOOLBARFLAG, main);
			getContext().startActivity(intent);
		}
	}

	/**
	 * dp转px
	 * 
	 * @author
	 * @param dp
	 * @return
	 */
	private float dpTopx(float dp) {
		float size = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
		return size;

	}

	/**
	 * Menu菜单隐藏时的动画
	 */
	private ScaleAnimation floatMenuOutScaleAnimation() {
		ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, 0.0f, 1.0f, 0.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		scaleAnimation.setFillAfter(false);
		scaleAnimation.setDuration(500);
		return scaleAnimation;
	}

	class HideMenuThread extends Thread {
		@Override
		public void run() {
			super.run();
		}
	}
}
